import { Op, Sequelize } from 'sequelize'
import { model } from '../model'
class UserDao {
  static userdao: UserDao = new UserDao()
  addUser(userifo: UserInfo) {
    return model.create(userifo)
  }
  findAllUser() {
    return model.findAll({ raw: true })
  }

  findByProps() {
    return model.findAll({ raw: true, attributes: ['username', 'psw'] })
  }

  findByUsrAndPsw(username: string, psw: string) {
    return model.findOne({
      raw: true,
      where: {
        [Op.and]: [
          {
            username
          },
          {
            psw
          }
        ]
      }
    })
  }

  findByLike(key: string) {
    const search = `%${key}%`
    return model.findAll({
      raw: true,
      where: {
        username: {
          [Op.like]: search
        }
      }
    })
  }

  findByUsrOrAddr(key: string) {
    return model.findAll({
      raw: true,
      where: {
        [Op.or]: [
          {
            username: {
              [Op.like]: `%${key}%`
            }
          },
          {
            address: {
              [Op.like]: `%${key}%`
            }
          }
        ]
      }
    })
  }

  countUserInfo() {
    return model.findAll({
      raw: true,
      group: 'address',
      attributes: ['address', [Sequelize.fn('count', Sequelize.col('valid')), 'total']],
      where: {
        valid: 1
      }
    })
  }

  findUserWithPager(limit: number, offset: number) {
    return model.findAll({
      raw: true,
      limit,
      offset
    })
  }
}

export type UserInfo = {
  userid: Number
  username: string
  psw: string
  address: string
  vaild: number
}

export const { userdao } = UserDao
